package grimbo.goodwinfooty.server.mvc;

import grimbo.goodwinfooty.server.ByteUtils;
import grimbo.goodwinfooty.server.MyData;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.google.appengine.api.datastore.Blob;

/**
 * @author paul
 * 
 */
public class TestJDOController extends AbstractController {
	private static final String CNAME = TestJDOController.class.getName();
	private static final Logger log = Logger.getLogger(CNAME);
	private PersistenceManagerFactory persistenceManagerFactory;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		final String MNAME = "handleRequestInternal(HttpServletRequest, HttpServletResponse)";
		final boolean DEBUG = log.isLoggable(Level.FINE);
		log.entering(CNAME, MNAME);

		String action = req.getParameter("action");

		res.setContentType("text/plain");

		PrintWriter w = res.getWriter();

		if ("load".equals(action)) {
			PersistenceManager pm = persistenceManagerFactory
					.getPersistenceManager();

			try {
				Query query = pm.newQuery(MyData.class);
				List list = (List) query.execute();
				log.info("found " + (null != list ? list.size() : "null")
						+ " items.");

				for (Iterator it = list.iterator(); it.hasNext();) {
					w.println(it.next());
				}
			} finally {
				pm.close();
			}
		} else if ("save".equals(action)) {
			PersistenceManager pm = persistenceManagerFactory
					.getPersistenceManager();

			try {
				MyData data = new MyData();
				data.setData(new Blob(ByteUtils.objectToBytes(new Date())));
				pm.makePersistent(data);
				w.println("saved " + data);
			} finally {
				pm.close();
			}
		} else {
			w.println("action not recognised");
		}

		log.exiting(CNAME, MNAME);

		return null;
	}

	public PersistenceManagerFactory getPersistenceManagerFactory() {
		return persistenceManagerFactory;
	}

	public void setPersistenceManagerFactory(
			PersistenceManagerFactory persistenceManagerFactory) {
		this.persistenceManagerFactory = persistenceManagerFactory;
	}
}
